package com.itheima.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;

    /**
     * 分页查询班级信息
     *
     * @param name
     * @param begin
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult pageClazz(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        //1.构建分页参数
        Page<Clazz> pageParam = Page.of(page, pageSize);

        //2.构建分页条件
        //3.发起分页查询
        Page<Clazz> pageResult = this.lambdaQuery().like(ObjectUtil.isNotEmpty(name) && name != null, Clazz::getName, name)
                .between(ObjectUtil.isNotEmpty(begin) && ObjectUtil.isNotEmpty(end), Clazz::getEndDate, begin, end)
                .page(pageParam);

        //4.为查询结果records添加班主任和状态
        List<Clazz> records = pageResult.getRecords();
        records.forEach(c -> {
            if (c.getEndDate().isBefore(LocalDate.now())) {
                c.setStatus("已结课");
            } else if (c.getEndDate().isAfter(LocalDate.now())) {
                c.setStatus("进行中");
            } else {
                c.setStatus("未开课");
            }
            c.setMasterName(empService.getById(c.getMasterId()).getName());
        });

        //5.返回结果
        return new PageResult(pageResult.getTotal(), records);
    }
}
